// $URL: http://mingw-lib.googlecode.com/svn/trunk/working/yt01/widget.cpp $
// $Rev: 62 $
// $Author: akio.miyoshi $
// $Date:: 2010-05-05 14:21:46 +0000#$

#include "widget.h"
#include "ui_widget.h"
#include <QtCore>
#include <QtGui>
#include <QtNetwork>
#include <QtXml>

#include "xmlutil.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    QWidget::setWindowFlags(Qt::WindowStaysOnTopHint); // top most
    nam = new NetworkAccessManager();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Widget::setDesktopFile(QFile &file, QString name)
{
    QString dirPath =
            QDesktopServices::storageLocation(
                    QDesktopServices::DesktopLocation);
    QDir dir(dirPath);
    QString filePath = dir.filePath(name);
    file.setFileName(filePath);
}

void Widget::saveDesktopFile(QString name, QByteArray bytes)
{
    QFile file;
    setDesktopFile(file, name);
    qDebug() << file.fileName();
    file.open(QIODevice::WriteOnly | QIODevice::Truncate);
    file.write(bytes);
}

void Widget::backupXmlBody(QByteArray bytes)
{
    saveDesktopFile("body.txt", bytes);
    QByteArray v_formated = XmlUtil::formatXml(bytes);
    saveDesktopFile("body2.txt", v_formated);
    qDebug() << QString::fromUtf8(v_formated.constData());
}

void Widget::parseXml(QByteArray &xml)
{
    QDomDocument domDocument;
    if(!XmlUtil::setXmlContent(domDocument, xml))
    {
        return;
    }
    QDomElement root = domDocument.documentElement();
    qDebug() << root.tagName();
    QDomElement child = root.firstChildElement("entry");
    while (!child.isNull()) {
        qDebug() << "child.tagName()" << child.tagName();
        QString title = child.firstChildElement("title").text();
        qDebug() << "[title]" << title;
        QString content = child.firstChildElement("content").text();
        qDebug() << "[content]" << content;
        QDomNodeList v_list = child.elementsByTagNameNS("http://search.yahoo.com/mrss/", "group");
        qDebug() << "v_list.count()" << v_list.count();
        QDomNode v_node = v_list.at(0);
        QDomElement v_elem = v_node.toElement();
        QDomNodeList v_list2 = child.elementsByTagNameNS("http://search.yahoo.com/mrss/", "description");
        QDomElement v_elem2 = v_list2.at(0).toElement();
        qDebug() << "[media:description(v_elem)]" << v_elem.text();
        qDebug() << "[media:description(v_elem2)]" << v_elem2.text();
        child = child.nextSiblingElement("entry");
    }
}

void Widget::on_pushButton_2_clicked()
{
    this->ui->pushButton_2->setEnabled(false);
    int startIndex = 1;
    int maxResults = 2;
    QUrl v_url;
    v_url.setUrl(
            QString::fromLatin1("http://gdata.youtube.com/feeds/api/users/akmiyoshi/favorites?start-index=%1&max-results=%2")
            .arg(startIndex).arg(maxResults)
            );
    QByteArray v_result = nam->doGet(v_url);
    backupXmlBody(v_result);
    parseXml(v_result);
    qApp->quit();
}

void Widget::parseXmlFor4U(QByteArray &xml)
{
    QDomDocument domDocument;
    if(!XmlUtil::setXmlContent(domDocument, xml))
    {
        qDebug() << "xml parse error!";
        return;
    }
    QDomElement root = domDocument.documentElement();
    qDebug() << root.tagName();
    QDomElement v_channel = root.firstChildElement("channel");

    QDomNodeList v_link_list = v_channel.elementsByTagNameNS("http://www.w3.org/2005/Atom", "link");
    for (int i=0; i<v_link_list.count(); i++)
    {
        QDomElement v_link = v_link_list.at(i).toElement();
        qDebug() << "[v_link.rel]" << v_link.attribute("rel");
    }

    QDomNodeList v_item_list = v_channel.elementsByTagNameNS("", "item");
    qDebug() << "v_item_list.count()" << v_item_list.count();

    for (int i=0; i<v_item_list.count(); i++)
    {
        Rec4U rec4u;
        QDomElement v_item = v_item_list.at(i).toElement();
        QString title = v_item.firstChildElement("title").text();
        qDebug() << "[title]" << title;
        rec4u.title = title;
        qDebug() << "[rec4u]" << rec4u;
        QDomNodeList v_thumb_list = v_item.elementsByTagNameNS("http://search.yahoo.com/mrss", "thumbnail");
        QDomElement v_thumb = v_thumb_list.at(0).toElement();
        qDebug() << "[v_thumb.url]" << v_thumb.attribute("url");
        QString v_large_url = v_thumb.attribute("url").replace("/m/m_", "/l/l_");
        qDebug() << v_large_url;
    }
}

void Widget::on_pushButton_clicked()
{
    this->ui->pushButton->setEnabled(false);
    int pageNo = 2;
    //int pageNo = 5163;
    //int pageNo = 5164;
    QUrl v_url;
    v_url.setUrl(
            QString::fromLatin1("http://4u.straightline.jp/rss?page=%1")
            .arg(pageNo)
            );
    QByteArray v_result = nam->doGet(v_url);
    backupXmlBody(v_result);
    parseXmlFor4U(v_result);
    qApp->quit();
}

void Widget::on_pushButton_3_clicked()
{
    QSettings settings(
            QSettings::IniFormat, //QSettings::NativeFormat,
            QSettings::UserScope, // QSettings::SystemScope,
            QCoreApplication::organizationName(),
            QCoreApplication::applicationName()
            );
    qDebug() << settings.value("twitpic/username").toString();
    qDebug() << settings.value("twitpic/password").toString();
    QUrl v_target;
    //v_target.setEncodedUrl("http://twitpic.com/api/uploadAndPost");
    v_target.setEncodedUrl("http://twitpic.com/api/upload");

    QNetworkRequest v_request;
    v_request.setUrl(v_target);
    v_request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=7d44e178b0434");

    QByteArray v_username = settings.value("twitpic/username").toString().toLatin1();
    QByteArray v_password = settings.value("twitpic/password").toString().toLatin1();

    QFile file;
    setDesktopFile(file, "thumb.jpg");
    qDebug() << file.fileName();
    file.open(QIODevice::ReadOnly);
    QByteArray thumb_binary = file.readAll();

    const char *NR="\n";
    QByteArray postData;
    QBuffer postBuffer;
    postBuffer.setBuffer(&postData);
    postBuffer.open(QIODevice::WriteOnly);

    postBuffer.write("--7d44e178b0434");
    postBuffer.write(NR);

    postBuffer.write("Content-Disposition: form-data; name=\"username\"");
    postBuffer.write(NR);
    postBuffer.write("Content-Type: text/plain;charset=UTF-8");
    postBuffer.write(NR);
    postBuffer.write(NR);
    postBuffer.write(v_username);
    postBuffer.write(NR);

    postBuffer.write("--7d44e178b0434");
    postBuffer.write(NR);

    postBuffer.write("Content-Disposition: form-data; name=\"password\"");
    postBuffer.write(NR);
    postBuffer.write("Content-Type: text/plain;charset=UTF-8");
    postBuffer.write(NR);
    postBuffer.write(NR);
    postBuffer.write(v_password);
    postBuffer.write(NR);

    postBuffer.write("--7d44e178b0434");
    postBuffer.write(NR);

    postBuffer.write("Content-Disposition: form-data; name=\"media\"; filename=\"");
    postBuffer.write(file.fileName().toUtf8());
    postBuffer.write("\"");
    postBuffer.write(NR);
    postBuffer.write("Content-Type: image/jpeg");
    postBuffer.write(NR);
    postBuffer.write("Content-Transfer-Encoding: binary");
    postBuffer.write(NR);
    postBuffer.write(NR);
    postBuffer.write(thumb_binary);
    postBuffer.write(NR);

    postBuffer.write("--7d44e178b0434--");
    postBuffer.write(NR);

    postBuffer.close();

    qDebug() << postData;

    QByteArray v_result = nam->doPost(v_request, postData);
    qDebug() << v_result;
}

void Widget::on_pushButton_4_clicked()
{
    QFile file;
    setDesktopFile(file, "rec.xml");
    qDebug() << file.fileName();
    file.open(QIODevice::ReadOnly);
    QByteArray xml = file.readAll();
    backupXmlBody(xml);
    QDomDocument domDocument;
    if(!XmlUtil::setXmlContent(domDocument, xml))
    {
        //return;
    }
    QDomElement root = domDocument.documentElement();
    qDebug() << root.tagName();
    qDebug() << root.attribute("class");
    QDomElement ul_class_entry_list = root.firstChildElement("ul");
    qDebug() << ul_class_entry_list.attribute("class");

    QByteArray text;
    QBuffer buff;
    buff.setBuffer(&text);
    buff.open(QIODevice::WriteOnly);
    QTextStream v_textout(&buff);
    const int IndentSize = 4;
    ul_class_entry_list.save(v_textout, IndentSize);

    qDebug() << "text=" << QString::fromUtf8(text);

}
